<?php defined('SYSPATH') or die('No direct script access.');

// Все, что не относитсяк другим моделям, пишем сюда
class Model_Main
{
    /*
    * Закачиваем картинку на сервер
    * 
    * Имя инпута, директория, ширина, имя
    * 
    * Пример вызова - upload_image('image', 'media/uploads/articles/')
    * 
    * Возврат - либо имя картинки, либо null
    */
	public function upload_image($input_name, $directory, $width = null, $filename = null)
    {
        $array = Validation::factory($_FILES);
        
        $array->rule($input_name, 'Upload::not_empty');            
        if($array->check())
        {                    
            // Закачиваем на сервер
            if(!$filename)
                $filename = time().mt_rand(0, 1000).'.jpg';
                
            $tmp_filename = Upload::save($_FILES[$input_name], $filename, $directory, 0755);
            
            // Закачали, теперь изменим размер            
            if($width)
            {
               $image = Image::factory($tmp_filename); 
               $image->resize($width, null)->save();
            }
        }
        else
        {
            $filename = null;
        }
        
        return $filename;
    }
    
    public function transliterate($str)
    {
        $tr = array(
            "А"=>"a","Б"=>"b","В"=>"v","Г"=>"g",
            "Д"=>"d","Е"=>"e","Ж"=>"j","З"=>"z","И"=>"i",
            "Й"=>"y","К"=>"k","Л"=>"l","М"=>"m","Н"=>"n",
            "О"=>"o","П"=>"p","Р"=>"r","С"=>"s","Т"=>"t",
            "У"=>"u","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
            "Ш"=>"sh","Щ"=>"sch","Ъ"=>"","Ы"=>"yi","Ь"=>"",
            "Э"=>"e","Ю"=>"yu","Я"=>"ya","а"=>"a","б"=>"b",
            "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
            "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
            "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
            "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
            "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
            "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya", 
            " "=> "-", "."=> "", "?" => "", "!" => "", "/"=> "-"
        );
        
        $result = strtr($str, $tr);
        
        if(preg_match('/[^A-Za-z0-9_\-]/', $result)) {
            $result = preg_replace('/[^A-Za-z0-9_\-]/', '', $result);
        }
        
        $result = str_replace('--', '-', $result);
        
        return strtolower($result);   
    }
    
    public function transliterate_array(&$array, $source_key, $dest_key = 'url')
    {
        foreach($array as &$item)
        {
            $item[$dest_key] = $this->transliterate($item[$source_key]);
        }        
        
        //return $array;
    }
    
    /*
    * Преобразует массив - ставит ключом элементов саммива id этого элемента
    * 
    * Пример - было {'0' => array('id' => 1, ...)}
    * стало         {'1' => array('id' => 1, ...)}
    */ 
    public function process_array($array, $id)
    {
        $result = array();
        for($i = 0; $i < count($array); $i++)
        {
            $result[$array[$i][$id]] = $array[$i];
        }
        
        return $result;  
    }
    
    // Делает первую букву заглавной
    public function ucfirst_utf8($str)
    {
        $fc = mb_strtoupper(mb_substr($str, 0, 1));
        return $fc.mb_substr($str, 1);   
    }
    
    public function rand_phrase(array $cases, $seed)
    {
        mt_srand($seed);
        
        $min = 0;
        $max = count($cases) - 1;
        
        $n = mt_rand($min, $max);
        
        return $cases[$n];
    }
} // End Main